package com.genius.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.genius.constant.SecurityConstants.HEADER_AUTH;

@Component
@EnableOpenApi
public class SwaggerConfig {
    /**
     * 原路径 http://127.0.0.1:8000/swagger-ui/index.html
     * 新路径 http://127.0.0.1:8000/doc.html
     * 配置swagger2核心配置docket
     */
    @Bean
    public Docket createRestApi() {

        // 指定api类型为OAS_30
        Docket docket = new Docket(DocumentationType.OAS_30);

        // 定义是否开启swagger，true开启，false关闭
        docket.enable(true);
        ApiInfoBuilder builder = new ApiInfoBuilder();
        builder.title("GK物联网平台");    // 文档页标题
        builder.contact(new Contact("genius", "https://www.geniusk.com", "geniusk_team@163.com"));  // 联系人信息
        builder.description("GeniusK物联网框架api文档");//   详细信息
        builder.version("1.0.1");   // 文档版本号
        builder.termsOfServiceUrl("https://www.geniusk.com");   //网站地址
        ApiInfo info = builder.build();
        docket.apiInfo(info);   // 用于定义api文档汇总信息

        //配置swagger中要添加的类和方法
        ApiSelectorBuilder selectorBuilder = docket.select();
        selectorBuilder.paths(PathSelectors.any());
        selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));     //方法加ApiOperation注解则添加到swagger页面
        docket = selectorBuilder.build();

        //配置swagger支持JWT
        ApiKey apiKey = new ApiKey(HEADER_AUTH, HEADER_AUTH, "header");
        List<SecurityScheme> securitySchemes = Collections.singletonList(apiKey);
        docket.securitySchemes(securitySchemes);

        //配置token令牌作用域
        AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");    //创建认证对象
        AuthorizationScope[] scopes = {scope};  //认证对象封装到数组
        SecurityReference reference = new SecurityReference(HEADER_AUTH, scopes);   //认证对象封装到SecurityReference
        List<SecurityReference> refList = new ArrayList<>();
        refList.add(reference);     //认证对象封装到SecurityReferenceList
        SecurityContext context = SecurityContext.builder().securityReferences(refList).build();
        List<SecurityContext> cxtList = new ArrayList<>();
        cxtList.add(context);   //认证对象封装到SecurityContextList
        docket.securityContexts(cxtList);

        return docket;
    }
}